import type { Directive } from 'vue';

interface ScrollData {
    handler: () => void;
    autoScrollEnabled: boolean;
}

const vScrollbottom: Directive = {
    mounted(el: HTMLElement) {
        // 初始滚动到底部
        el.scrollTop = el.scrollHeight;

        const scrollData: ScrollData = {
            autoScrollEnabled: true,
            handler: () => {
                // 容差判断是否滚动到底部
                const isAtBottom =
                    Math.abs(el.scrollHeight - el.scrollTop - el.clientHeight) <
                    10;
                scrollData.autoScrollEnabled = isAtBottom;
            },
        };

        el.addEventListener('scroll', scrollData.handler);

        // 挂载数据供 updated 使用
        (el as any).__scrollData__ = scrollData;

        (el as any).__vueScrollUpdate__ = () => {
            if (scrollData.autoScrollEnabled) {
                el.scrollTop = el.scrollHeight;
            }
        };
    },
    updated(el: HTMLElement) {
        const updateFn = (el as any).__vueScrollUpdate__;
        if (updateFn) {
            updateFn();
        }
    },
    beforeUnmount(el: HTMLElement) {
        const scrollData = (el as any).__scrollData__;
        if (scrollData && scrollData.handler) {
            el.removeEventListener('scroll', scrollData.handler);
        }
        delete (el as any).__vueScrollUpdate__;
        delete (el as any).__scrollData__;
    },
};

export default vScrollbottom;
